package com.jeesite.modules.exam.score.service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.assessment.service.DcSupExamInfoService;
import com.jeesite.modules.exam.notice.entity.DcSupExamNotice;
import com.jeesite.modules.exam.notice.service.DcSupExamNoticeService;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaAdd;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaInfoService;
import com.jeesite.modules.exam.score.entity.*;
import com.jeesite.modules.exam.score.vo.DcSupExamQuotaOrgVo;
import com.jeesite.modules.exam.score.vo.DcSupExamVo;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.home.entity.cuibanDto;
import com.jeesite.modules.msg.entity.content.PcMsgContent;
import com.jeesite.modules.msg.utils.MsgPushUtils;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.OfficeUtil;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.deploy.entity.OfficeUser;
import com.jeesite.modules.yzw.entity.MsgDetail;
import com.jeesite.modules.yzw.service.LehandYzwPushTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.exam.score.dao.DcSupExamScoreDao;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

/**
 * 考核任务指标评分表Service
 *
 * @author xhc
 * @version 2022-06-01
 */
@Slf4j
@Service
@Transactional(readOnly=false)
@RequiredArgsConstructor
public class DcSupExamScoreService extends CrudService<DcSupExamScoreDao, DcSupExamScoreInfo> {


    private final SysOfficeUnitService sysOfficeUnitService;

    private final DcSupExamSumQuotaInfoService dcSupExamSumQuotaInfoService;

    private final LehandYzwPushTask lehandYzwPushTask;

    private final EmpUserService empUserService;

    private final DcSupExamNoticeService dcSupExamNoticeService;

    private final DcSupTaskActionDao dcSupTaskActionDao;

    private final DcSupExamInfoService dcSupExamInfoService;

    private final DcSupBacklogService dcSupBacklogService;
    /**
     * 获取单条数据
     *
     * @param dcSupExamScoreInfo
     * @return
     */
    @Override
    public DcSupExamScoreInfo get(DcSupExamScoreInfo dcSupExamScoreInfo) {
        return super.get(dcSupExamScoreInfo);
    }

    /**
     * 查询分页数据
     *
     * @param dcSupExamScoreInfo 查询条件
     * @param
     * @return
     */
    @Override
    public Page<DcSupExamScoreInfo> findPage(DcSupExamScoreInfo dcSupExamScoreInfo) {
        return super.findPage(dcSupExamScoreInfo);
    }

    /**
     * 查询列表数据
     *
     * @param dcSupExamScoreInfo
     * @return
     */
    @Override
    public List<DcSupExamScoreInfo> findList(DcSupExamScoreInfo dcSupExamScoreInfo) {
        return super.findList(dcSupExamScoreInfo);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param dcSupExamScoreInfo
     */
    @Override
    @Transactional(readOnly = false)
    public void save(DcSupExamScoreInfo dcSupExamScoreInfo) {
        super.save(dcSupExamScoreInfo);
    }

    /**
     * 更新状态
     *
     * @param dcSupExamScoreInfo
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(DcSupExamScoreInfo dcSupExamScoreInfo) {
        super.updateStatus(dcSupExamScoreInfo);
    }

    /**
     * 删除数据
     *
     * @param dcSupExamScoreInfo
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(DcSupExamScoreInfo dcSupExamScoreInfo) {
        super.delete(dcSupExamScoreInfo);
    }


    /**
     * 创建评分主表对象
     *
     * @param examId
     * @param noticeId
     * @param scoreType
     * @param contactName
     * @param contactPhone
     * @return
     */
    public DcSupExamScore createNewDcSupExamScore(String examId, String noticeId, String scoreType, String contactName, String contactPhone,String scoreStatus,String quotaId) {
        DcSupExamScore dcSupExamScore = new DcSupExamScore();
        dcSupExamScore.setId(IdGen.nextId());
        dcSupExamScore.setExamId(examId);
        dcSupExamScore.setNoticeId(noticeId);
        dcSupExamScore.setScoreType(scoreType);
        dcSupExamScore.setContactName(contactName);
        dcSupExamScore.setContactPhone(contactPhone);
        dcSupExamScore.setCreateBy(UserUtils.getUser().getUserCode());
        dcSupExamScore.setCreateByName(UserUtils.getUser().getUserName());
        dcSupExamScore.setCreateDate(new Date());
        dcSupExamScore.setScoreStatus(scoreStatus);//确认分数
        dcSupExamScore.setQuotaId(quotaId);
        return dcSupExamScore;
    }

    /**
     * 创建评分表对象
     *
     * @param dcSupExamSumQuotaInfo
     * @param dcSupExamScore
     * @return
     */
    public DcSupExamScoreInfo createNewDcSupExamScoreInfo(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo, DcSupExamScore dcSupExamScore) {
        DcSupExamScoreInfo dcSupExamScoreInfo = new DcSupExamScoreInfo();
        dcSupExamScoreInfo.setId(IdGen.nextId());
        dcSupExamScoreInfo.setScoreId(dcSupExamScore.getId());
        dcSupExamScoreInfo.setScoreSource("1");//指标汇总
        dcSupExamScoreInfo.setQuotaId(dcSupExamSumQuotaInfo.getId());
        dcSupExamScoreInfo.setQuotaWeight(dcSupExamSumQuotaInfo.getQuotaWeight());
        dcSupExamScoreInfo.setQuotaScore(dcSupExamSumQuotaInfo.getQuotaScore());
        dcSupExamScoreInfo.setQuotaUnit(dcSupExamSumQuotaInfo.getQuotaUnit());
        dcSupExamScoreInfo.setPercentage(dcSupExamSumQuotaInfo.getPercentage());
        dcSupExamScoreInfo.setScoreReason(dcSupExamSumQuotaInfo.getScoreReason());
        return dcSupExamScoreInfo;
    }

    public DcSupExamScoreInfo createNewDcSupExamScoreInfo(DcSupExamQuotaAdd dcSupExamQuotaAdd, DcSupExamScore dcSupExamScore) {
        DcSupExamScoreInfo dcSupExamScoreInfo = new DcSupExamScoreInfo();
        dcSupExamScoreInfo.setId(IdGen.nextId());
        dcSupExamScoreInfo.setScoreId(dcSupExamScore.getId());
        dcSupExamScoreInfo.setScoreSource("2");//加减分项
        dcSupExamScoreInfo.setQuotaId(dcSupExamQuotaAdd.getId());
        dcSupExamScoreInfo.setQuotaWeight(dcSupExamQuotaAdd.getQuotaWeight());
        dcSupExamScoreInfo.setQuotaScore(dcSupExamQuotaAdd.getQuotaScore());
        dcSupExamScoreInfo.setQuotaUnit(dcSupExamQuotaAdd.getQuotaUnit());
        return dcSupExamScoreInfo;
    }

    /**
     * 创建汇总表对象
     * @param dcSupExamSumQuotaInfo
     * @param exameOrg
     * @param exameOrgName
     * @return
     */
    public DcSupExamSumScore createNewDcSupExamSumScore(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo, String exameOrg, String exameOrgName) {
        DcSupExamSumScore dcSupExamSumScore = new DcSupExamSumScore();
        dcSupExamSumScore.setId(IdGen.nextId());
        dcSupExamSumScore.setExamId(dcSupExamSumQuotaInfo.getExamId());
        dcSupExamSumScore.setQuotaId(dcSupExamSumQuotaInfo.getId());
        dcSupExamSumScore.setQuotaScore(dcSupExamSumQuotaInfo.getQuotaScore());
        dcSupExamSumScore.setSumStatus("1");//草稿状态
        dcSupExamSumScore.setExameOrg(exameOrg);
        dcSupExamSumScore.setExameOrgName(exameOrgName);
        dcSupExamSumScore.setScoreOrg(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        dcSupExamSumScore.setScoreOrgName(sysOfficeUnitService.getLatestUnitByOffice().getOfficeName());
        dcSupExamSumScore.setCreateBy(UserUtils.getUser().getUserCode());
        dcSupExamSumScore.setCreateByName(UserUtils.getUser().getUserName());
        dcSupExamSumScore.setCreateDate(new Date());
        dcSupExamSumScore.setScoreSource("1");
        if ("3".equals(dcSupExamSumQuotaInfo.getQuotaClass())||"2".equals(dcSupExamSumQuotaInfo.getQuotaClass())){
            dcSupExamSumScore.setScoreSource("2");
        }
        dcSupExamSumScore.setScoreReason(dcSupExamSumQuotaInfo.getScoreReason());
        dcSupExamSumScore.setPercentage(dcSupExamSumQuotaInfo.getPercentage());
        dcSupExamSumScore.setQuotaWeight(dcSupExamSumQuotaInfo.getQuotaWeight());
        return dcSupExamSumScore;
    }


    public DcSupExamSumScore createNewDcSupExamSumScore(DcSupExamQuotaAdd dcSupExamQuotaAdd,String examId, Office exameOrg, Office scoreOrg) {
        DcSupExamSumScore dcSupExamSumScore = new DcSupExamSumScore();
        dcSupExamSumScore.setId(IdGen.nextId());
        dcSupExamSumScore.setExamId(examId);
        dcSupExamSumScore.setQuotaId(dcSupExamQuotaAdd.getId());
        dcSupExamSumScore.setQuotaScore(dcSupExamQuotaAdd.getQuotaScore());
        dcSupExamSumScore.setSumStatus("2");//汇总才用到，直接发布状态
        dcSupExamSumScore.setExameOrg(exameOrg.getOfficeCode());
        dcSupExamSumScore.setExameOrgName(exameOrg.getOfficeName());
        dcSupExamSumScore.setScoreOrg(scoreOrg.getOfficeCode());
        dcSupExamSumScore.setScoreOrgName(scoreOrg.getOfficeName());
        dcSupExamSumScore.setScoreOrg(OfficeUtil.getCurrentOffice().getOfficeCode());
        dcSupExamSumScore.setScoreOrgName(OfficeUtil.getCurrentOffice().getOfficeName());
        dcSupExamSumScore.setCreateBy(UserUtils.getUser().getUserCode());
        dcSupExamSumScore.setCreateByName(UserUtils.getUser().getUserName());
        dcSupExamSumScore.setCreateDate(new Date());
        dcSupExamSumScore.setScoreSource("2");
        dcSupExamSumScore.setQuotaWeight(dcSupExamQuotaAdd.getQuotaWeight());
        dcSupExamSumScore.setScoreReason(dcSupExamQuotaAdd.getScoreReason());
        dcSupExamSumScore.setPercentage(dcSupExamQuotaAdd.getPercentage());
        return dcSupExamSumScore;
    }




    /**
     * 获取自评评分列表
     *
     * @param dcSupExamNotice
     * @return
     */
    public List<DcSupExamSumQuotaInfo> findZpListData(DcSupExamNotice dcSupExamNotice) {
        // 获取当前用户编号
        String userCode = UserUtils.getUser().getUserCode();
        String officeCode = "";
        // 过滤管理员
        if (!StringUtils.equals("system", userCode)) {
            officeCode= sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode();
        }
        return super.dao.findZpListData(dcSupExamNotice, officeCode);
    }

    /**
     * 获取评分主表信息
     *
     * @param examId
     * @param noticeId
     * @param scoreType
     * @return
     */
    public DcSupExamScore findDcSupExamScore(DcSupExamScore dcSupExamScore) {
//        String examId, String noticeId, String scoreType,String examOrg,String quotaId,String gradeOrg
        return super.dao.findDcSupExamScore(dcSupExamScore);
    }


    /**
     * 获取被考核单位
     *
     * @param examId
     * @param quotaGroup
     * @return
     */
    public List<DcSupExamQuotaOrgVo> findAssessmentUnit(String examId, String quotaGroup) {
        List<DcSupExamQuotaOrgVo> assessmentUnit = super.dao.findAssessmentUnit(examId, quotaGroup);
        DcSupExamScore dcSupExamScore = new DcSupExamScore();
        dcSupExamScore.setExamId(examId);
        dcSupExamScore.setScoreStatus("2");
        dcSupExamScore.setScoreType("2");
        List<DcSupExamScore> dcSupExamScores = findDcSupExamScoreList(dcSupExamScore);
            List<String> subExamOrgs = dcSupExamScores.stream().map(x -> x.getExameOrg()).collect(Collectors.toList());
            for (DcSupExamQuotaOrgVo dcSupExamQuotaOrgVo : assessmentUnit) {
                String exameOrg = dcSupExamQuotaOrgVo.getExameOrg();
                dcSupExamQuotaOrgVo.setExameStatus("4");
                if (subExamOrgs.contains(exameOrg)) {
                    dcSupExamQuotaOrgVo.setExameStatus("5");
                }
            }
        return assessmentUnit;
    }

    /**
     * 获取关键指标评分列表
     *
     * @param dcSupExamNotice
     * @param exameOrg
     * @return
     */
    public List<DcSupExamSumQuotaInfo> findGJListData(String examId, String exameOrg) {
        return super.dao.finGjpListData(examId, exameOrg);
    }

    /**
     * 获取单项指标评分列表
     *
     * @param dcSupExamNotice
     * @param exameOrg
     * @return
     */
    public List<DcSupExamSumQuotaInfo> findDXListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
        List<DcSupExamSumQuotaInfo> dxListData = super.dao.findDXListDataPage(dcSupExamSumQuotaInfo);
        return dxListData;
    }


    /**
     * 自评提交
     *
     * @param dcSupExamVo
     */
    @Transactional
    public void saveZpScore(DcSupExamVo dcSupExamVo) {
        String examId = dcSupExamVo.getDcSupExamNotice().getExamId();
        String noticeId = dcSupExamVo.getDcSupExamNotice().getId();
        Office currentOffice = sysOfficeUnitService.getLatestUnitByOffice();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setNoticeId(noticeId);
        dcSupExamScoreVo.setScoreType("1");
        dcSupExamScoreVo.setExameOrg(currentOffice.getOfficeCode());
        DcSupExamScore dcSupExamScore = findDcSupExamScore(dcSupExamScoreVo);
        if (dcSupExamScore != null) {
            throw new ServiceException("当前分数已确认过了！");
        }
        dcSupExamScore = createNewDcSupExamScore(examId, noticeId, "1", null,null,"1",null);
        //自评 考核单位和被考核单位都是自己
        dcSupExamScore.setScoreOrg(currentOffice.getOfficeCode());
        dcSupExamScore.setScoreOrgName(currentOffice.getOfficeName());
        dcSupExamScore.setExameOrg(currentOffice.getOfficeCode());
        dcSupExamScore.setExameOrgName(currentOffice.getOfficeName());
        super.dao.insertDcSupExamScore(dcSupExamScore);
        //插入评分数据
        List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamVo.getDcSupScoreList();
        List<DcSupExamScoreInfo> scoreInfoList = new ArrayList<>();
        for (DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo : dcSupExamSumQuotaInfos) {
            //准备打分数据
            DcSupExamScoreInfo newDcSupExamScoreInfo = createNewDcSupExamScoreInfo(dcSupExamSumQuotaInfo, dcSupExamScore);
            //准备汇总数据
            scoreInfoList.add(newDcSupExamScoreInfo);
        }
        //插入打分数据
        super.dao.insertDcSupExamListScore(scoreInfoList);
    }


    /**
     * 提交自评
     * @param dcSupExamVo
     */
    public void subZpScore(DcSupExamVo dcSupExamVo) {
        String examId = dcSupExamVo.getDcSupExamNotice().getExamId();
        String noticeId = dcSupExamVo.getDcSupExamNotice().getId();
        String contactName = dcSupExamVo.getDcSupExamScore().getContactName();
        String contactPhone = dcSupExamVo.getDcSupExamScore().getContactPhone();
        String officeCode = sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setNoticeId(noticeId);
        dcSupExamScoreVo.setScoreType("1");
        dcSupExamScoreVo.setExameOrg(officeCode);
        DcSupExamScore dcSupExamScore = findDcSupExamScore(dcSupExamScoreVo);
        if (dcSupExamScore==null){
            throw new ServiceException("请先确认分数！");
        }
        if ("2".equals(dcSupExamScore.getScoreStatus())){
            throw new ServiceException("请勿重复提交！");
        }
        dcSupExamScore.setContactName(contactName);
        dcSupExamScore.setContactPhone(contactPhone);
        dcSupExamScore.setScoreStatus("2");
        //保存确认分数
        super.dao.updateDcSupExamScore(dcSupExamScore);
        //文件保存
        FileUploadUtils.saveFileUpload(dcSupExamScore.getId(), "dcSupExamScore_file", dcSupExamVo.getFileUploadIds(), "");
    }


    /**
     * 关键指标评分提交
     *
     * @param dcSupExamVo
     */
    @Transactional
    public void saveGJScore(DcSupExamVo dcSupExamVo) {
        String examId = dcSupExamVo.getExamId();
        Office office = EmpUtils.getOffice(dcSupExamVo.getExameOrg());
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setScoreType("2");
        dcSupExamScoreVo.setExameOrg(dcSupExamVo.getExameOrg());
        DcSupExamScore dcSupExamScore = findDcSupExamScore(dcSupExamScoreVo);
        if (dcSupExamScore != null) {
            if(StringUtils.isNotBlank(dcSupExamScore.getScoreStatus())){
                throw new ServiceException("当前评分已提交过了！");
            }
            dao.deleteDcSupExamSumScoreById(dcSupExamScore);
            dao.deleteDcSupExamScoreInfoByScoreId(dcSupExamScore);
            dao.deleteDcSupExamScoreById(dcSupExamScore);
        }
        dcSupExamScore = createNewDcSupExamScore(examId, null, "2", null, null,"2",null);
        //获取打分单位
        Office currentOffice = sysOfficeUnitService.getLatestUnitByOffice();
        dcSupExamScore.setScoreOrg(currentOffice.getOfficeCode());
        dcSupExamScore.setScoreOrgName(currentOffice.getOfficeName());
        //获取被打分单位
        List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamVo.getDcSupScoreList();
        dcSupExamScore.setExameOrg(office.getOfficeCode());
        dcSupExamScore.setExameOrgName(office.getOfficeName());
        super.dao.insertDcSupExamScore(dcSupExamScore);
        //插入评分数据
        List<DcSupExamScoreInfo> scoreInfoList = new ArrayList<>();
        List<DcSupExamSumScore> sumScoreList = new ArrayList<>();
        for (DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo : dcSupExamSumQuotaInfos) {
            //校验打分数据
            checkScoreGJ(dcSupExamSumQuotaInfo.getQuotaWeight(),dcSupExamSumQuotaInfo.getQuotaScore(),dcSupExamSumQuotaInfo.getPercentage());
            //准备打分数据
            DcSupExamScoreInfo newDcSupExamScoreInfo = createNewDcSupExamScoreInfo(dcSupExamSumQuotaInfo, dcSupExamScore);
            //准备汇总数据
            DcSupExamSumScore newDcSupExamSumScore = createNewDcSupExamSumScore(dcSupExamSumQuotaInfo,office.getOfficeCode(), office.getOfficeName());
            scoreInfoList.add(newDcSupExamScoreInfo);
            sumScoreList.add(newDcSupExamSumScore);
        }
        //插入打分数据
        super.dao.insertDcSupExamListScore(scoreInfoList);
        //插入汇总数据
        super.dao.insertDcSupExamListSumScore(sumScoreList);
        //文件保存
        FileUploadUtils.saveFileUpload(dcSupExamScore.getId(), "dcSupExamScore_file", dcSupExamVo.getFileUploadIds(), "");
        //关键指标评分处理
    }

    public void checkScore(Double quotaWeight,Double quotaScore,Double percentage){
        if (quotaWeight==null||quotaScore==null||percentage==null||percentage>100){throw new ServiceException("数据异常，评分失败！");}
//        BigDecimal b1 = new BigDecimal(quotaWeight.toString());
//        BigDecimal b2 = new BigDecimal(percentage.toString());
//        BigDecimal baseQuotaScore = new BigDecimal(quotaScore.toString());
//        BigDecimal percentageBd = b2.movePointLeft(2);
//        //保留三位小数 并且四舍五入
//        BigDecimal quotaScoreBd = percentageBd.multiply(b1).setScale(3, BigDecimal.ROUND_HALF_UP);
        if (quotaScore>quotaWeight){throw new ServiceException("数据异常，评分失败！");}
    }
    public void checkScoreGJ(Double quotaWeight,Double quotaScore,Double percentage){
        if (quotaWeight==null||quotaScore==null||percentage==null||percentage>120){throw new ServiceException("数据异常，评分失败！");}

    }


    /**
     * 提交单项指标评分
     *
     * @param dcSupExamVo
     */
    public void saveDXScore(DcSupExamVo dcSupExamVo) {
        //获取打分单位
        Office currentOffice = sysOfficeUnitService.getLatestUnitByOffice();
        String examId = dcSupExamVo.getDcSupExamScore().getExamId();
        String noticeId = dcSupExamVo.getDcSupExamNotice().getId();
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setNoticeId(noticeId);
        dcSupExamScoreVo.setScoreType("3");
        dcSupExamScoreVo.setQuotaId(dcSupExamVo.getQuotaId());
        dcSupExamScoreVo.setExameOrg(currentOffice.getOfficeCode());
        DcSupExamScore dcSupExamScore = findDcSupExamScore(dcSupExamScoreVo);
        if (dcSupExamScore != null) {
            throw new ServiceException("当前评分已提交过了！");
        }
        dcSupExamScore = createNewDcSupExamScore(examId, noticeId, "3", null, null,"1",dcSupExamVo.getQuotaId());

        List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamVo.getDcSupScoreList();
        //获取被打分单位
        dcSupExamScore.setScoreOrg(currentOffice.getOfficeCode());
        dcSupExamScore.setScoreOrgName(currentOffice.getOfficeName());
        dcSupExamScore.setQuotaId(dcSupExamVo.getQuotaId());
        super.dao.insertDcSupExamScore(dcSupExamScore);
        //插入评分数据
        List<DcSupExamScoreInfo> scoreInfoList = new ArrayList<>();
        List<DcSupExamSumScore> sumScoreList = new ArrayList<>();
        for (DcSupExamSumQuotaInfo baseDcSupExamSumQuotaInfo : dcSupExamSumQuotaInfos) {
            checkScore(baseDcSupExamSumQuotaInfo.getQuotaWeight(),baseDcSupExamSumQuotaInfo.getQuotaScore(),baseDcSupExamSumQuotaInfo.getPercentage());
            DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo = dcSupExamSumQuotaInfoService.get(baseDcSupExamSumQuotaInfo.getId());
            dcSupExamSumQuotaInfo.setPercentage(baseDcSupExamSumQuotaInfo.getPercentage());
            dcSupExamSumQuotaInfo.setQuotaScore(baseDcSupExamSumQuotaInfo.getQuotaScore());
            dcSupExamSumQuotaInfo.setExamId(examId);
            //准备打分数据
            DcSupExamScoreInfo newDcSupExamScoreInfo = createNewDcSupExamScoreInfo(dcSupExamSumQuotaInfo, dcSupExamScore);
            newDcSupExamScoreInfo.setExameOrg(dcSupExamSumQuotaInfo.getExameOrg());
            newDcSupExamScoreInfo.setExameOrgName(dcSupExamSumQuotaInfo.getExameOrgName());
            newDcSupExamScoreInfo.setScoreReason(baseDcSupExamSumQuotaInfo.getScoreReason());
            //准备汇总数据
            DcSupExamSumScore newDcSupExamSumScore = createNewDcSupExamSumScore(dcSupExamSumQuotaInfo, dcSupExamSumQuotaInfo.getExameOrg(), dcSupExamSumQuotaInfo.getExameOrgName());
            newDcSupExamSumScore.setScoreReason(baseDcSupExamSumQuotaInfo.getScoreReason());
            scoreInfoList.add(newDcSupExamScoreInfo);
            sumScoreList.add(newDcSupExamSumScore);
        }
        //插入打分数据
        super.dao.insertDcSupExamListScore(scoreInfoList);
        //插入汇总数据
        super.dao.insertDcSupExamListSumScore(sumScoreList);
    }

    public static Double sub(Double value1, Double value2) {

        BigDecimal b1 = new BigDecimal(Double.toString(value1));

        BigDecimal b2 = new BigDecimal(Double.toString(value2));

        return b1.subtract(b2).doubleValue();

    }

    public List<DcSupExamQuotaAdd> findDxQuotaAddList(DcSupExamNotice dcSupExamNotice, String exameOrg) {
        return super.dao.findDxQuotaAddList(dcSupExamNotice,exameOrg);
    }

    public List<DcSupExamScore> findDcSupExamScoreList(DcSupExamScore dcSupExamScore) {
        return super.dao.findDcSupExamScoreList(dcSupExamScore);
    }


    public void subDXScore(DcSupExamVo dcSupExamVo) {
        String examId = dcSupExamVo.getDcSupExamNotice().getExamId();
        String noticeId = dcSupExamVo.getDcSupExamNotice().getId();
        String contactName = dcSupExamVo.getDcSupExamScore().getContactName();
        String contactPhone = dcSupExamVo.getDcSupExamScore().getContactPhone();
        Office latestUnitByOffice = sysOfficeUnitService.getLatestUnitByOffice();
        DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo = new DcSupExamSumQuotaInfo();
        dcSupExamSumQuotaInfo.setExamId(examId);
        dcSupExamSumQuotaInfo.setGradeOrg(latestUnitByOffice.getOfficeCode());
        dcSupExamSumQuotaInfo.setPage(null);

        List<DcSupExamSumQuotaInfo> dxListData = findDXListData(dcSupExamSumQuotaInfo);
        List<String> status = dxListData.stream().map(x -> x.getScoreStatus()).collect(Collectors.toList());
        long count1 = status.stream().filter(x -> "1".equals(x)).count();
        long count2 = status.stream().filter(x -> "2".equals(x)).count();

        if (count1<status.size()){
            throw new ServiceException("请先确认分数在提交！");
        }
        if (count2>0){
            throw new ServiceException("请勿重复提交分数！");
        }

        DcSupExamScore dcSupExamScore = createNewDcSupExamScore(examId, noticeId, "3", contactName, contactPhone, "2", null);
        dcSupExamScore.setScoreOrg(latestUnitByOffice.getOfficeCode());
        //保存确认分数
        List<String> quotaIds = dxListData.stream().map(x -> x.getId()).collect(Collectors.toList());
        String fileId=IdGen.nextId();
        dcSupExamScore.setFileId(fileId);
        super.dao.updateDcSupDXExamScore(dcSupExamScore,quotaIds);
        //文件保存
        FileUploadUtils.saveFileUpload(fileId, "dcSupExamScore_file", dcSupExamVo.getFileUploadIds(), "");
        //是否发送短信
        DcSupExamNotice dcSupExamNotice = dcSupExamNoticeService.get(noticeId);
        sendDxMessageNotice(examId,dcSupExamNotice.getCreateBy());

        //单项细指标评分处理单项指标评分通知
        dcSupBacklogService.doBacklog(dcSupExamSumQuotaInfo.getExamId(),"exam_submit_score",dcSupExamSumQuotaInfo.getExameOrg());
    }


    private void sendDxMessageNotice(String examId,String createBy){
        if (StringUtils.isBlank(examId)){
            throw new ServiceException("examId 不能为空！");
        }
        CompletableFuture.runAsync(()->{
            //查询当前已经提交的单项指标数量
            DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
            dcSupExamScoreVo.setExamId(examId);
            dcSupExamScoreVo.setScoreStatus("2");
            dcSupExamScoreVo.setScoreType("3");
            List<DcSupExamScore> dcSupExamScoreList = findDcSupExamScoreList(dcSupExamScoreVo);

            //查询单项指标数量
            DcSupExamSumQuotaInfo dcSupExamSumQuotaInfoVo = new DcSupExamSumQuotaInfo();
            dcSupExamSumQuotaInfoVo.setExamId(examId);
            List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = findDXListData(dcSupExamSumQuotaInfoVo);
            log.info("提交评分数据:{},所有指标数据:{}",dcSupExamScoreList,dcSupExamSumQuotaInfos);

            EmpUser empUser = new EmpUser();
            empUser.getEmployee().getOffice().setIsQueryChildren(true);
            empUser.getEmployee().getCompany().setIsQueryChildren(true);
            empUser.setRoleCode("OTS_ORG");
            empUser.setUserCode(createBy);
            List<EmpUser> userList = empUserService.findList(empUser);
            String msg="所有评分单位已评分，请及时登录系统查看";
            if (dcSupExamSumQuotaInfos.size()>0&&dcSupExamScoreList.size()==dcSupExamSumQuotaInfos.size()){
                userList.forEach(x->{
//                    PcMsgContent pcMsgContent = new PcMsgContent();
//                    pcMsgContent.setTitle("提示信息");
//                    pcMsgContent.setContent(msg);
//                    MsgPushUtils.push(pcMsgContent,examId, "scorenotice", x.getUserCode());

                    MsgDetail msgDetail = new MsgDetail();
                    msgDetail.setSubjectid(x.getUserCode());
                    msgDetail.setMesg(msg);
                    //指定发送人为张洁
                    msgDetail.setSendid("16356");
                    lehandYzwPushTask.pushScoreShortMsg(msgDetail);
                    dcSupBacklogService.add("目标考核","评分汇总","评分汇总通知","提示信息"
                            ,msg.replace("登录系统","")
                            ,"/score/dcSupExamSumScore/sumScoreListView",""
                            ,examId,"exam_sum_score",x.getUserCode()
                            ,"","");

                });
            }
        });
    }



    public Map<String, Object> findUnitScoreListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
        List<DcSupExamSumQuotaInfo> unitScoreListData = super.dao.findUnitScoreListData(dcSupExamSumQuotaInfo);
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(dcSupExamSumQuotaInfo.getExamId());
        dcSupExamScoreVo.setNoticeId(dcSupExamSumQuotaInfo.getNoticeId());
        dcSupExamScoreVo.setScoreType("3");
        dcSupExamScoreVo.setQuotaId(dcSupExamSumQuotaInfo.getId());
        dcSupExamScoreVo.setScoreOrg(dcSupExamSumQuotaInfo.getGradeOrg());
        DcSupExamScore dcSupExamScore = findDcSupExamScore(dcSupExamScoreVo);
        Map<String, Object> map = new HashMap<>();
        unitScoreListData.forEach(x->{
            if ("3".equals(x.getQuotaClass())&&StringUtils.isBlank(x.getScoreStatus())) {
                x.setQuotaScore(x.getQuotaWeight());
            }
        });
        map.put("data",unitScoreListData);
        map.put("score",dcSupExamScore);
        map.put("showSubView",findDxSaveLength(dcSupExamSumQuotaInfo));
        return map;
    }

    public Page<DcSupExamSumQuotaInfo> findDXListDataPage(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
        Office latestUnitByOffice = sysOfficeUnitService.getLatestUnitByOffice();
        if (StringUtils.isBlank(dcSupExamSumQuotaInfo.getGradeOrg())){
            dcSupExamSumQuotaInfo.setGradeOrg(latestUnitByOffice.getOfficeCode());
        }
        List<DcSupExamSumQuotaInfo> dxListData = super.dao.findDXListDataPage(dcSupExamSumQuotaInfo);
        return dcSupExamSumQuotaInfo.getPage().setList(dxListData);
    }


    public String findDxSaveLength(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
        //1未确认分数  2已确认未提交 3 已提交
        dcSupExamSumQuotaInfo.setPage(null);
        List<DcSupExamSumQuotaInfo> dxListData = findDXListData(dcSupExamSumQuotaInfo);
        List<String> status = dxListData.stream().map(x -> x.getScoreStatus()).collect(Collectors.toList());
        long count1 = status.stream().filter(x -> "1".equals(x)).count();
        long count2 = status.stream().filter(x -> "2".equals(x)).count();
        if (count2==status.size()){
            return "3";
        }
        if (count1<status.size()){
            return "1";
        }
        if (count1==status.size()){
            return "2";
        }
        return "1";
    }

    public List<DcSUpExamDxExport> exportDxScore(DcSupExamScore dcSupExamScore) {
        Office latestUnitByOffice = sysOfficeUnitService.getLatestUnitByOffice();
        dcSupExamScore.setScoreOrg(latestUnitByOffice.getOfficeCode());
        return super.dao.exportDxScore(dcSupExamScore);
    }

    public Page<DcSupExamInfo> gjIndexListData(DcSupExamInfo dcSupExamInfo) {
        List<DcSupExamInfo> dcSupExamInfos = super.dao.gjIndexListData(dcSupExamInfo);
        return dcSupExamInfo.getPage().setList(dcSupExamInfos);
    }

    public List<DcSupExamScore> findDxExamScoreList(DcSupExamScore dcSupExamScore) {
        return super.dao.findDxExamScoreList(dcSupExamScore);
    }

    public List<Map<String, String>> getNoScoreGradeOrg(String examId, String examOrg) {
        return super.dao.getNoScoreGradeOrg(examId,examOrg);
    }

    public void cuiban(DcSupExamSumScore dcSupExamSumScore) {
        DcSupExamInfo dcSupExamInfo = dcSupExamInfoService.get(dcSupExamSumScore.getExamId());
        //获取要催的单位
        List<Map<String, String>> list = getNoScoreGradeOrg(dcSupExamSumScore.getExamId(),dcSupExamSumScore.getExameOrg());
        Thread thread = new Thread(() -> {
            for (int i = 0; i < list.size(); i++) {
                List<OfficeUser> userByOrg = dcSupTaskActionDao.getUserByOrg("EL_ORG", list.get(i).get("gradeOrg"));
                for (int j = 0; j < userByOrg.size(); j++) {
                    PcMsgContent msg = new PcMsgContent();
                    msg.setTitle("提示信息");
                    msg.addButton("单项指标评分", "/a/notice/dcSupExamNotice/dxNoticeView");
                    msg.setContent("您有一个评分:" + dcSupExamInfo.getExamTitle() + "被催办!");
                    MsgPushUtils.push(msg, dcSupExamSumScore.getId(), "pingfenhuizongcuiban", userByOrg.get(j).getUserCode());
                    //发送易政网消息
                    MsgDetail msgDetail = new MsgDetail();
                    msgDetail.setSendid(UserUtils.getUser().getUserCode());
                    msgDetail.setSubjectid(userByOrg.get(j).getUserCode());
                    System.out.println("催办人"+userByOrg.get(j).getUserCode());
                    msgDetail.setMesg("您有一个评分:\"" + dcSupExamInfo.getExamTitle() + "\"被催办,请及时登录系统查看");
                    lehandYzwPushTask.pushYzwShortMsg(msgDetail);
                }
            }
        });
        thread.start();
    }

    public List<DcSupExamQuotaOrgVo> dxScoreStepInfo(String examId) {
        //获得任务打分单位
        DcSupExamInfo dcSupExamInfo = dcSupExamInfoService.get(examId);
        Assert.notNull(dcSupExamInfo,"考核任务不存在！");
        List<DcSupExamQuotaOrgVo> assessmentUnit = super.dao.findScoreOrgByexamId(examId, "2");
        DcSupExamScore dcSupExamScore = new DcSupExamScore();
        dcSupExamScore.setExamId(examId);
        dcSupExamScore.setScoreStatus("2");
        dcSupExamScore.setScoreType("3");
        List<DcSupExamScore> dxdcSupExamScores = super.dao.findDxaffirmList(dcSupExamScore);

        for (DcSupExamQuotaOrgVo dcSupExamQuotaOrgVo : assessmentUnit) {
            dcSupExamQuotaOrgVo.setExamYear(dcSupExamInfo.getExamYear());
            dcSupExamQuotaOrgVo.setExamTitle(dcSupExamInfo.getExamTitle());
            long count = dxdcSupExamScores.stream().filter(x -> x.getScoreOrg().equals(dcSupExamQuotaOrgVo.getGradeOrg())).count();
            dcSupExamQuotaOrgVo.setDxStepStatus("0");
            if (count>0){
                dcSupExamQuotaOrgVo.setDxStepStatus("1");
            }
        }
        return assessmentUnit;
    }

    public void cuibanDXCK(cuibanDto cuiban) {
        String message = cuiban.getMessage();
        for (int i = 0; i < cuiban.getUserList().size(); i++) {
            cuiban.setPhone(cuiban.getUserList().get(i).getPhone());
            cuiban.setUserCode(cuiban.getUserList().get(i).getUserCode());
            PcMsgContent msg = new PcMsgContent();
            msg.setTitle("提示信息");
            msg.setContent(message);
            msg.addButton("指标评分", "/a/notice/dcSupExamNotice/dxNoticeView");
            MsgPushUtils.push(msg, cuiban.getId(), "danxiangzhibiaopinfencuiban", cuiban.getUserList().get(i).getUserCode());
            //发送易政网消息
            cuiban.setMessage(cuiban.getUserList().get(i).getName() + ","+cuiban.getMessage());
            //cuiban.setMessage(cuiban.getUserList().get(i).getName() + ",您有一个单项指标评分被催办,请及时登录系统查看");
            lehandYzwPushTask.pushYzwShortMsg2(cuiban);
        }
    }

    public int dxWithdraw(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo) {
        return dao.dxWithdraw(dcSupExamSumQuotaInfo);
    }
    @Transactional(readOnly = false)
    public void updateScoreInfo(DcSupExamSumScore score) {
        //通过id查询原有的自评scoreInfo数据
        DcSupExamScoreInfo info = dao.queryScoreInfoById(score);
        DcSupExamSumScore score_db = new DcSupExamSumScore();
        score_db.setExamId(score.getExamId());
        score_db.setExameOrg(info.getExameOrg());
        score_db.setScoreOrg(score.getScoreOrg());
        score_db.setQuotaId(info.getQuotaId());

        //更新info表分数，百分比，原因
      if(dao.updateScoreInfo(score)+dao.updateSumScore(score,score_db)!=2){
          throw new ServiceException("修改失败");
      }
    }
    @Transactional(readOnly = false)
    public void withDrawGJScore(String examId, String exameOrg) {
        DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
        dcSupExamScoreVo.setExamId(examId);
        dcSupExamScoreVo.setScoreType("9");
        DcSupExamScore dcSupExamScore = this.findDcSupExamScore(dcSupExamScoreVo);
        if(dcSupExamScore!=null){
            throw new ServiceException("撤回失败,只有评分汇总所有单位【已提交前状态】可撤回");
        }
        dcSupExamScoreVo.setScoreType("2");
        dcSupExamScoreVo.setExameOrg(exameOrg);
       int update = dao.withDrawGJScore(dcSupExamScoreVo);
       if(update!=1){
           throw new ServiceException("撤回失败");
       }
    }
}